// pages/address/address.js
const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  //选择地址
  selectAddress(e) {
    //获取页面传递的地址信息
    const address = e.currentTarget.dataset.address; //将地址信息中的楼栋与门牌号拼接成获得完整的快递地址
    const returnAddress = `${address.building}-${address.doorNum}`; //获取页面栈（数组）
    const pages = getCurrentPages(); //页面数组pages长度-2，为上一页
    const prevPage = pages[pages.length - 2]; //将获得的地址赋值给上一页的form.address
    prevPage.setData({ "form.address": returnAddress }); //返回上一页
    wx.navigateBack({ delta: 1 });
  },
  addAddress() {
    wx.navigateTo({
      url: "../addressAdd/addressAdd",
    });
  },
  //删除地址
  delAddress(e) {
    wx.showModal({
      cancelColor: "#2052A3",
      confirmColor: "#F5273C",
      title: "提示",
      content: "您确认删除所选信息么",
      success: (res) => {
        if (res.confirm) {
          //获取需要删除的地址数组索引
          const idx = e.currentTarget.dataset.index;
          const address = this.data.address;
          //采用splice删除数组元素，并将删除的地址赋值给delAddress
          const delAddress = address.splice(idx, 1);
          //取出删除的地址id
          const _id = delAddress[0]._id;
          //发送服务端进行删除
          wx.request({
            url: `${app.globalData.server}/wxDelAddress?_id=${_id}`,
            success: (res) => {
              if (res.data == "success") {
                //删除成功 刷新页面
                wx.showToast({ title: "删除成功" });
                this.onShow();
              } else {
                //删除失败
                wx.showToast({ title: "删除失败" });
              }
            },
            fail: (error) => {
              console.log(error);
              wx.showToast({ title: "删除失败" });
            },
          });
        }
      },
    });
  },
  //修改地址
  updateAddress(e) {
    const idx = e.currentTarget.dataset.index;
    const address = this.data.address[idx];
    wx.setStorageSync("addressInfo", address);
    wx.navigateTo({ url: `../addressAdd/addressAdd` });
  },
  //读取地址信息
  getAddress() {
    wx.showLoading({ title: "地址加载中...." });
    wx.request({
      url: `${app.globalData.server}/wxAddress`,
      data: { openid: app.globalData.userInfo.openid },
      success: (res) => {
        wx.hideLoading();
        if (res.data.message == "success") {
          this.setData({
            address: res.data.result,
            hasAddress: true,
          });
        } else {
          wx.showToast({ title: "服务器错误", icon: "error" });
        }
      },
      fail: (err) => {
        console.log(err);
        wx.showToast({ title: "服务器错误" });
      },
    });
  },
  data: {
    address: [], //地址数组,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {},

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    //清空地址缓存 防止修改地址信息时，未保存而后退时，未清理缓存
    wx.removeStorageSync("addressInfo");
    //判断登录
    if (!app.globalData.userInfo.openid) {
      wx.showModal({
        title: "温馨提示",
        content: "您尚未登陆，请先授权登录再试！",
        showCancel: false,
        success: () => {
          wx.switchTab({ url: "../user/person/person" });
          return;
        },
      });
    } else {
      //调用getAddress方法，读取地址
      this.getAddress();
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {},
});
